package com.auth.common.util.security.attestation;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang3.time.DateUtils;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {

    /**
     * SECRET 密钥
     */
    public static final String SECRET = "cyj:auth:1.0";

    public static final String INFO = "info";

    /**
     * Create token string
     *
     * @param jsonInfo    jsonInfo
     * @param expireTime expire time
     * @return the string
     * @description: 生成 token
     */
    public static String createToken(String jsonInfo, int expireTime) {
        Map<String, Object> header = new HashMap<>(10);
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        String token = null;
        try {
            token = JWT.create()
                    .withHeader(header)
                    .withClaim(INFO, jsonInfo)
                    .withSubject("token")
                    // 签名时间
                    .withIssuedAt(new Date())
                    //过期时间
                    .withExpiresAt(DateUtils.addSeconds(new Date(), expireTime))
                    .sign(Algorithm.HMAC256(SECRET));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("生成token 异常");
        }
        return token;
    }

    /**
     * Verify token map
     *
     * @param token token
     * @return the map
     * @description: 解密token, 如果过期抛异常
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            throw new RuntimeException("解密token 异常");
        }
        return jwt.getClaims();
    }

    /**
     * Parse token map
     *
     * @param token token
     * @return the map
     * @description: 解密token
     */
    public static Map<String, Claim> parseToken(String token) {
        DecodedJWT decodedJwt = JWT.decode(token);
        return decodedJwt.getClaims();
    }

    public static void main(String[] args) {
        String token = JWTUtil.createToken("[]", 1000);
        Map<String, Claim> claims = JWTUtil.parseToken(token);
        //用户ID
        String loginId = claims.get(INFO).asString();
        System.out.println(loginId);
    }

}
